package com.twq.patternmatch.extractors

/**
 * Created by tangweiqun on 2017/11/22.
 */
object ExtractorUnapplySeq {

  def main(args: Array[String]): Unit = {
    isTomInDotCom("tom@spark.cn.sun.com") //res3: Boolean = true
    isTomInDotCom("peter@sun.com") //res4: Boolean = false
    isTomInDotCom("tom@acm.org") //res5: Boolean = false


    val s = "tom@support.epfl.ch"
    val ExpandedEMail(name, topdom, subdoms@_*) = s
  }

  def isTomInDotCom(s: String) = s match {
    case EMail("tom", Domain("com", e@_*)) => println(e) //用变量e绑定_*
    case _ =>
  }

  List(1, 2, 3) match {
    case List() => println("empty")
    case List(x, y, _*) => println(x + " " + y)
    case List(x, 0, 0, _) => println(x)
  }


}

object Domain {
  //spark.edu.com.cn
  // The injection method (optional)
  def apply(parts: String*): String =
    parts.reverse.mkString(".")

  // The extraction method (mandatory)
  def unapplySeq(whole: String): Option[Seq[String]] = {
    println("Domain unapplySeq used")
    //cn com edu spark
    Some(whole.split("\\.").reverse)

  }

}

object ExpandedEMail {
  def unapplySeq(email: String)
  : Option[(String, Seq[String])] = {
    val parts = email split "@"
    if (parts.length == 2)
      Some(parts(0), parts(1).split("\\.").reverse)
    else
      None
  }
}


